package Smallprogram.dao;

import java.sql.*;

public class BaseDao {
    Connection conn = null;

    public Connection getConnection() {

        //1.加载驱动
        try {
            if(conn==null || conn.isClosed()) {
                Class.forName("com.mysql.cj.jdbc.Driver");
                conn = DriverManager.getConnection("jdbc:mysql://123.56.132.182:3306/BurgerKingDB?serverTimezone=GMT-8&useUnicode=true&characterEncoding=utf-8","dbAdmin","BurgerKing@123");
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }

    /**
     * 关闭连接
     *
     * @param conn
     * @param pstmt
     */
    public void closeConnection(Connection conn, PreparedStatement pstmt, ResultSet rs) {
        try {
            if(rs!=null){
                rs.close();
            }
            if (pstmt != null) {
                pstmt.close();
            }
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

    /**
     * 增删改
     *
     * @param sql    sql语句
     * @param params 参数
     * @return
     */
    public int executeUpdate(String sql, Object... params) {
        conn = this.getConnection();
        PreparedStatement pstmt = null;
        int row = 0;//受影响的行数
        //2.创建连接
        try {
            //4.创建搬运工
            pstmt = conn.prepareStatement(sql);

            //5.给参数赋值
            for (int i = 0; i < params.length; i++) {
                // pstmt.setObject(1,params[0])
                // pstmt.setObject(2,params[1])
                // pstmt.setObject(3,params[2])
                pstmt.setObject(i + 1, params[i]);
            }
            //6.执行sql 语句
            row = pstmt.executeUpdate();

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            //8.关闭
            this.closeConnection(conn, pstmt,null);
        }
        return row;
    }

    /**
     * 查询
     * @param sql sql 语句
     * @param params 参数
     * @return 结果集
     */
    public ResultSet executeQuery(String sql, Object... params) {
        conn = this.getConnection();
        PreparedStatement pstmt = null;
        ResultSet rs = null;//返回的结果集
        try {
            pstmt = conn.prepareStatement(sql);
            //5.给参数赋值
            for (int i = 0; i < params.length; i++) {
                pstmt.setObject(i + 1, params[i]);
            }
            rs = pstmt.executeQuery();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return rs;
    }
}
